//
//  YYOauthViewModel.swift
//  SinaWeibo
//
//  Created by Apple on 16/5/9.
//  Copyright © 2016年 devshaw. All rights reserved.
//

import UIKit

class YYOauthViewModel: NSObject {


        func loadToken(code: String,sucess: ()->(),failed: ()->()){
            let urlString = "https://api.weibo.com/oauth2/access_token"


            let parameters = ["client_id":Appkey,
                "client_secret":Appsecret,
                "grant_type":"authorization_code",
                "code":code,
                "redirect_uri":OpenURL
            ]
            YYHTTPClient.shareInstance.requset(.POST, URLString: urlString, parameters: parameters, success: { (_, JSON) -> Void in
                printLog(JSON)

                if let json = JSON as? [String: AnyObject]{

                    let model =  YYUserAccount(dic: json)

                    printLog(model.access_token)


                    self.loadInfo(model, success: sucess, failed: failed)
                }
                }) { (_, error) -> Void in
                    printLog(error)
            }
        }
    





        private func loadInfo(model: YYUserAccount,success: ()->(),failed:()->()){


            guard let uid = model.uid , token = model.access_token else{
                return
            }

            let urlString = "https://api.weibo.com/2/users/show.json"

            let params = ["access_token":token,"uid":uid]

            YYHTTPClient.shareInstance.request(.GET , URLString: urlString, parameters: params, progress: nil, success: { (_, JSON) -> Void in





                if let json = JSON as?[String: AnyObject]{
                    let name = json["screen_name"] as? String
                    model.screen_name = name

                    model.profile_image_url = json["profile_image_url"] as? String

                    printLog( model.profile_image_url)


                    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
                    
                    let filePath = (path as NSString).stringByAppendingPathComponent("info.abc")
                    
                    NSKeyedArchiver.archiveRootObject(model, toFile: filePath)
                    
                    
                    
                    success()
                    
                }
                
                
                
                }) { (_, error) -> Void in
                    printLog(error)

                    failed()
            }
        }

}